package com.franklin.ideaplugin.easytesting.editor;

import cn.hutool.core.io.FileUtil;
import com.franklin.ideaplugin.easytesting.cache.IEasyTestingCache;
import com.franklin.ideaplugin.easytesting.cache.impl.PersistenceEasyTestingCache;
import com.franklin.ideaplugin.easytesting.entity.ExecuteResult;
import com.franklin.ideaplugin.easytesting.vfs.ExecuteMethodVirtualFile;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiMethod;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author Franklin
 * @since 2023/07/31 20:55
 */
public abstract class BaseExecuteMethodScriptEditorProvider extends BaseExecuteMethodEditorProvider{

    /**
     * 获取脚本文件
     * @param project
     * @param executeMethodVirtualFile
     * @return
     */
    protected VirtualFile getScriptFile(Project project,ExecuteMethodVirtualFile executeMethodVirtualFile){
        PsiMethod interfaceClassName = executeMethodVirtualFile.getPsiMethod();

        ExecuteResult executeResult = executeMethodVirtualFile.getExecuteResult();
        PersistenceEasyTestingCache easyTestingCache = (PersistenceEasyTestingCache) IEasyTestingCache.getInstance(project);
        String code = "";
        VirtualFile scriptFile = null;
        String path = "";
        if (Objects.nonNull(executeResult)) {
            path = easyTestingCache.getScriptPath(interfaceClassName,executeResult);
            File file = FileUtil.file(path);
            if (Objects.nonNull(file)) {
                if (!file.exists()){
                    code = ExecuteMethodTransformerBuilder.buildScript(interfaceClassName);
                    FileUtil.writeString(code,path, StandardCharsets.UTF_8);
                }else {
                    code = FileUtil.readString(path,StandardCharsets.UTF_8);
                }
            }
        }else {
            code = ExecuteMethodTransformerBuilder.buildScript(interfaceClassName);
        }
        path = easyTestingCache.getExecuteScriptPath(interfaceClassName);
        FileUtil.writeString(code,path, StandardCharsets.UTF_8);
        scriptFile = getFile(FileUtil.file(path));
        return scriptFile;
    }

    private VirtualFile getFile(File file){
        return VirtualFileManager.getInstance().refreshAndFindFileByNioPath(file.toPath());
    }
}
